#pragma once

#include <iostream>
#include <stdarg.h>
#include <ctime>
#include <cstring>
#include <cerrno>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <cstdlib>
using namespace std;

#define Info 1    // 常规消息
#define Warning 2 // 警告消息
#define Error 3   // 错误消息，需要立即处理
#define Fatal 4   // 致命错误
#define Debug 5   // 调试消息

#define Screen 1
#define Onefile 2
#define Classfile 3

#define SIZE 1024
#define LogFile "log.txt"

// 日志格式：默认部分 + 自定义部分
class Log
{
public:
    Log()
    {
        printMethod = Screen;
        path = "./log/";
    }

    void Enable(int method)
    {
        printMethod = method;
    }

    string levelToString(int level)
    {
        switch (level)
        {
        case Info:
            return "Info";
        case Warning:
            return "Warning";
        case Error:
            return "Error";
        case Fatal:
            return "Fatal";
        case Debug:
            return "Debug";
        default:
            return "None";
        }
    }

    void operator()(int level, const char *format, ...)
    {
        time_t t = time(nullptr);
        struct tm *ctime = localtime(&t);

        char leftbuffer[SIZE];
        snprintf(leftbuffer, sizeof(leftbuffer), "[%s][%d-%d-%d %d:%d:%d]", levelToString(level).c_str(),
                 ctime->tm_year + 1900, ctime->tm_mon + 1, ctime->tm_mday,
                 ctime->tm_hour, ctime->tm_min, ctime->tm_sec);

        va_list s;
        va_start(s, format);
        char rightbuffer[SIZE];
        vsnprintf(rightbuffer, sizeof(rightbuffer), format, s);
        va_end(s);

        char logtxt[SIZE * 2];
        snprintf(logtxt, sizeof(logtxt), "%s %s\n", leftbuffer, rightbuffer);

        printLog(level, logtxt);
    }

    void printOneFile(const string& logname, const string& logtxt)
    {
        cout << logname << endl;
        string filename = path + logname;
        int fd = open(filename.c_str(), O_WRONLY|O_CREAT|O_APPEND, 0666);
        if(fd < 0)
        {
            cout << filename << endl;
            cout << strerror(errno) << endl;
            return;
        }
        write(fd, logtxt.c_str(), logtxt.size());
        close(fd);
    }

    void printClassFile(int level, const string& logtxt)
    {
        string filename = LogFile;
        filename += ".";
        filename += levelToString(level);
        printOneFile(filename, logtxt);
    }

    void printLog(int level, const string& logtxt)
    {
        switch(printMethod)
        {
        case Screen:
            cout << logtxt << endl;
            break;
        case Onefile:
            printOneFile(LogFile, logtxt);
            break;
        case Classfile:
            printClassFile(level, logtxt);
            break;
        default:
            break;
        }
    }

private:
    int printMethod;
    string path;
};